package com.neusoft.neu24.nep.sentinel;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.neusoft.neu24.nep.entity.CommonResult;
import com.neusoft.neu24.nep.entity.HttpCodeEnum;
import org.springframework.stereotype.Component;
// 因为需要被Springboot注入，所以其所在的包必须是Boot启动类的子包
@Component  // 注入到Spring容器中
public class NepSentinelBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(jakarta.servlet.http.HttpServletRequest request,
                       jakarta.servlet.http.HttpServletResponse response,
                       BlockException e) throws Exception {
        CommonResult  result = null;
         if (e instanceof FlowException ){
             result =  new CommonResult<>(HttpCodeEnum.BLOCK_BY_FlowException) ;
         }else if ( e  instanceof DegradeException){
             result =  new CommonResult<>(HttpCodeEnum.LIMIT_DOWNGRADED_RESPONSE) ;
         }else {
             result =  new CommonResult<>(HttpCodeEnum.LIMIT_DOWNGRADED_RESPONSE) ;
         }
//         设置响应的数据格式内容
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(200);
        response.setCharacterEncoding("utf-8");
        response.setHeader("ContentType","application/json;charset=utf-8");
        new ObjectMapper()
                .writeValue(
                        response.getWriter(),
                        result
                );
    }
}
